package com.tb.rabbit.receiver;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 业务消息消费者
 * @author tangbin
 */
@Component
@Slf4j
public class BusinessMessageReceiver {
    /**
     * 两个业务队列
     */
    public static final String BUSINESS_QUEUEA_NAME="dead.letter.demo.simple.business.queuea";
    public static final String BUSINESS_QUEUEB_NAME="dead.letter.demo.simple.business.queueb";
    /**
     * 消费消息
     */
    @RabbitListener(queues = BUSINESS_QUEUEA_NAME)
    public void receiveA(Message message, Channel channel) throws IOException {
        String msg=new String(message.getBody());
        log.info("BusinessMessageA：{}", msg);
        boolean ack=true;
        Exception exception=null;
        try {
            if (msg.contains("deadletter")){
                throw new RuntimeException("dead letter exception");
            }
        } catch (RuntimeException e) {
            ack=false;
            exception=e;
        }
        if (!ack){
            log.info("error msg：{}", exception.getMessage());
            //设置死信消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }else {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
    /**
     * 消息信息B
     */
    @RabbitListener(queues = BUSINESS_QUEUEB_NAME)
    public void receiveB(Message message,Channel channel) throws IOException {
        String msg = new String(message.getBody());
        log.info("BusinessMessageB：{}", msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
